package com.liu.webstore.service.impl;

import com.liu.webstore.entity.Comment;
import com.liu.webstore.enums.StatusEnum;
import com.liu.webstore.repository.CommentMapper;
import com.liu.webstore.repository.DiscussPostMapper;
import com.liu.webstore.service.CommentService;
import com.liu.webstore.util.SensitiveWordFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.util.HtmlUtils;

import java.util.List;
import java.util.Objects;

/**
 * @Author LiuYumei
 * @Date 2022/7/25 22:15
 */
@Service
public class CommentServiceImpl implements CommentService {
    private static Logger log = LoggerFactory.getLogger(CommentServiceImpl.class);
    @Autowired
    private SensitiveWordFilter sensitiveWordFilter;

    @Autowired
    private CommentMapper commentMapper;

    @Autowired
    private DiscussPostMapper discussPostMapper;

    @Override
    public List<Comment> findCommentsByEntity(int entityType, int entityId, int offert, int limit) {
        return commentMapper.selectCommentsByEntity(entityType, entityId, offert, limit);
    }

    @Override
    public int findCommentCount(int entityType, int entityId) {
        return commentMapper.selectCountByEntity(entityType, entityId);
    }

    @Transactional(
            isolation = Isolation.READ_COMMITTED,
            propagation = Propagation.REQUIRED,
            rollbackFor = Exception.class
    )
    @Override
    public int addComment(Comment comment) {
        if (Objects.isNull(comment)) {
            log.error("参数不能为空！");
        }
        comment.setContent(HtmlUtils.htmlEscape(comment.getContent()));
        comment.setContent(sensitiveWordFilter.filter(comment.getContent()));
        int rows = commentMapper.insertComment(comment);
        if (rows < 1) {
            log.error("添加评论失败！");
        }
        // 更新帖子评论数量
        if (comment.getEntityType() == StatusEnum.ENTITY_TYPE_POST.getStatus()) {
            int count = commentMapper.selectCountByEntity(comment.getEntityType(), comment.getEntityId());
            int row = discussPostMapper.updateCommentCount(comment.getEntityId(), count);
            if (row < 1) {
                log.error("更新帖子评论数量失败！");
            }
        }
        return rows;
    }

    @Override
    public Comment findCommentById(int id) {
        return commentMapper.selectCommentById(id);
    }
}
